#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "task.h"

typedef void(*func_t)();

#define N 3

func_t task[3] = { NULL };

void LoadTask()
{
    task[0] = PrintfLog;
    task[1] = DownLoad;
    task[2] = MysqlDataSync;
}

void HanderTask()
{
    for (int i = 0; i < N; i++)
    {
        task[i]();
    }
}

void DofatherThing()
{
    HanderTask();
}


void ChildRun()
{
    int cnt = 5;
   // int *p = NULL;
    while (cnt)
    {
        printf("I am child process,pid:%d, ppid:%d, cnt:%d\n", getpid(), getppid(), cnt);
        cnt--;
        sleep(1);
       // *p = 100;
    }
}

int main()
{
    printf("I am father process,pid:%d, ppid:%d\n", getpid(), getppid());

    pid_t id = fork();
    if (id == 0)
    {
        //child
       ChildRun();
       printf("child quit...\n");
       exit(1);
    }
    LoadTask();
    //father
    while (1)
    {
        int status = 0;
        pid_t rid = waitpid(id, &status, WNOHANG);
        if (rid == 0)
        {
            usleep(100000);
            printf("child is running, father check next time!\n");
           DofatherThing();
        }
        else if (rid > 0) 
        {
            if (WIFEXITED(status))
            {
                printf("Child quit success, child exit code:%d\n", WEXITSTATUS(status));
            }
            else 
            {
                printf("Child quit unnormal!\n");
            }
            break;
        }
        else 
        {
            printf("waitpid failed!\n");
            break;
        }
    }

   // else 
   // {
   //     //sleep(7);
   //     int status = 0;
   //     //father
   //     //pid_t rid = wait(NULL);
   //     pid_t rid = waitpid(id, &status, 0);
   //     if (rid > 0)
   //     {
   //         if (WIFEXITED(status))
   //         {
   //             printf("Child quit success, child exit code:%d\n", WEXITSTATUS(status));
   //         }
   //         else 
   //         {
   //             printf("Child quit unnormal!\n");
   //         }
   //         printf("wait sucess, rid:%d, status:%d, child_quit_code:%d, child_quit_signal:%d\n", rid, status, (status>>8)&0xff, status&0x7f);
   //     }
   //     else 
   //     {
   //         printf("wait failed, status:%d\n", status);
   //     }
   //     sleep(3);
   // }

    return 0;
}
